/*
 * Master.cpp
 *
 *  Created on: May 13, 2011
 *      Author: stud
 */


#include "Master.h"
#include "SerialPort.h"
#include "ModbusProtocol.h"

mbPacket Master::getPacketIn()
{
	return this->packetIn;
}

mbPacket Master::getPacketOut()
{
	return this->packetOut;
}

void Master::flushPacketBuffer()
{
	protocol->createReadRequest(&packetIn,0x00,0x00,0x00);
	protocol->createReadRequest(&packetOut,0x00,0x00,0x00);
}

void Master::flushQueryBuffer()
{
	for(int i = 0; i< QUERY_BUFF_SIZE; i++)
	{
		protocol->createReadRequest(&(queries[i]),0x00,0x00,0x00);
	}
}

Master::Master(ThreadPriority pri, string _name, MemoryMaps * mapManager,char * device, int baudRate) : Thread(pri, _name)
{
	xbee = new SerialPort(device,baudRate);
	xbee->serialPortInit();

	protocol = new ModbusProtocol();

	_maps = mapManager;

	flushPacketBuffer();
	flushQueryBuffer();
};

void Master::executeRead()
{
	protocol->createReadRequest(&packetOut,0x01,0x14,0x00);
	protocol->serializeReadRequest(buffer,packetOut);
	protocol->addCRC(buffer,6);

	xbee->writeBlock(buffer,8);

	xbee->readBlock(buffer,45);

	protocol->deserializeReadResponse(buffer,&packetIn);

#ifdef _debug
	protocol->printReadResponse(packetIn);
#endif

	fflush(stdout);
}

void Master::executeWrite()
{
	sWord data;

	data.Word = 0xA;

	protocol->createWriteRequest(&packetOut,0x1,data,0x01);
	protocol->serializeWriteRequest(buffer,packetOut);
	protocol->addCRC(buffer,6);

	xbee->writeBlock(buffer,8);
	xbee->readBlock(buffer,8);

	protocol->deserializeWriteResponse(buffer,&packetIn);
	protocol->printWriteResponse(packetIn);
	fflush(stdout);
}

void Master::executeWrite(sWord * dataOut, int len)
{
	int i=0;
	for(i=0;i<len;i++)
	{
		protocol->createWriteRequest(&packetOut,0x1,dataOut[i],i);
		protocol->serializeWriteRequest(buffer,packetOut);
		protocol->addCRC(buffer,6);

		xbee->writeBlock(buffer,8);
		xbee->readBlock(buffer,8);
		protocol->deserializeWriteResponse(buffer,&packetIn);
		protocol->printWriteResponse(packetIn);
		fflush(stdout);


	}
}

void Master::run()
{
	int i=0;

	sWord testArray[20];

	int flag=0;

	for(i=0;i<20;i++)
	{
		testArray[i].Word = (unsigned short)i;
	}
		while(1) // Declare the periodic actions for the data monitor
		{

			i = i++;
			executeRead();

#ifndef _debug

			flag = _maps->getWriteMapFlag();

			if (flag == 0)
			{
				_maps->setMapContents(0,packetIn.tail.readPacketResponse.data);
			}
			else
			{
				executeWrite(_maps->getMapContents(0,testArray),20);
				_maps->writeFlagDown();
			}
#endif



			sleep(1);
		}

};

Master::~Master()
{
	xbee->close();
};



